package edu.scau.ojforwarder.service;

import edu.scau.ojforwarder.bean.HduError;
import edu.scau.ojforwarder.bean.HduStatus;
import edu.scau.ojforwarder.bean.HduSubmission;
import edu.scau.ojforwarder.bean.BaseResult;
import edu.scau.ojforwarder.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class HduService {

    @Autowired
    private HduClient hduClient;

    @Autowired
    private HduSubmitTask submitTask;

    @Autowired
    private HduStatusManager statusManager;

    public BaseResult<HduStatus> addSubmission(HduSubmission submission) {
        String submissionId = submitTask.addSubmission(submission);
        HduStatus status = statusManager.getStatus(submissionId);
        return ResultGenerator.genResult(HduError.SUCCESS, status);
    }

    public BaseResult<HduStatus> getStatus(String submissionId) {
        HduStatus status = statusManager.getStatus(submissionId);
        if (status == null)
            return ResultGenerator.genResult(HduError.NO_SUCH_SUBMISSION);
        if (status.getStatus().equals("Queuing") ||
                status.getStatus().equals("Compiling") ||
                status.getStatus().equals("Running")) {
            statusManager.updateStatus(status.getCid());
            status = statusManager.getStatus(submissionId);
        }
        if (status.getError() != null)
            return ResultGenerator.genResult(status.getError(), status);
        else
            return ResultGenerator.genResult(HduError.SUCCESS, status);
    }

    public BaseResult<String> getProblemDesc(String cid, String pid) {
        try {
            String problemDesc = hduClient.fetchProblemDesc(cid, pid);
            return ResultGenerator.genResult(HduError.SUCCESS, problemDesc);
        } catch (ErrorException e) {
            return ResultGenerator.genResult(e.getError());
        }
    }

}
